import 'package:flutter/material.dart';
import '../demo/ui_demo.dart';
import 'dart:math';
import 'dart:io' ;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:path_provider/path_provider.dart';
import 'package:audio_recorder/audio_recorder.dart';
import '../wonders/utils/utils.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:permission_handler/permission_handler.dart';
class MyDemo extends StatelessWidget implements Demo {
  MyDemo(this.title);
  @override
  final String title;
  @override
  Widget build(BuildContext context) {
    return new HomePage(
      title: this.title,
    );
  }
}

class HomePage extends StatefulWidget {
  final String title;
  HomePage({this.title});
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Plugin audio recorder'),
        ),
        body: new AppBody(),
      ),
    );
  }
}

class AppBody extends StatefulWidget {
  final LocalFileSystem localFileSystem;

  AppBody({localFileSystem})
      : this.localFileSystem = localFileSystem ?? LocalFileSystem();

  @override
  State<StatefulWidget> createState() => new AppBodyState();
}

class AppBodyState extends State<AppBody> {
  Recording _recording = new Recording();
  bool _isRecording = false;
  Random random = new Random();
  TextEditingController _controller = new TextEditingController();
  String _authInfo;
  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Padding(
        padding: new EdgeInsets.all(8.0),
        child: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              new FlatButton(
                onPressed: _isRecording ? null : _start,
                child: new Text("Start"),
                color: Colors.green,
              ),
              new FlatButton(
                onPressed: _isRecording ? _stop : null,
                child: new Text("Stop"),
                color: Colors.red,
              ),
              new TextField(
                controller: _controller,
                decoration: new InputDecoration(
                  hintText: 'Enter a custom path',
                ),
              ),
              new Text("File path of the record: ${_recording.path}"),
              new Text("Format: ${_recording.audioOutputFormat}"),
              new Text("Extension : ${_recording.extension}"),
              new Text(
                  "Audio recording duration : ${_recording.duration.toString()}")
            ]),
      ),
    );
  }

  _start() async {
    await requestPermission();
    try {
        if (_controller.text != null && _controller.text != "") {
          String path = _controller.text;
          if (!_controller.text.contains('/')) {
            Directory appDocDirectory =
            await getApplicationDocumentsDirectory();
            path = appDocDirectory.path + '/' + _controller.text;
          }
          print("Start recording: $path");
          await AudioRecorder.start(
              path: path, audioOutputFormat: AudioOutputFormat.WAV);
        } else {
          await AudioRecorder.start();
        }
        bool isRecording = await AudioRecorder.isRecording;
        setState(() {
          _recording = new Recording(duration: new Duration(), path: "");
          _isRecording = isRecording;
        });

    } catch (e) {
      print(e);
    }
  }

  _stop() async {
    var recording = await AudioRecorder.stop();
    print("Stop recording: ${recording.path}");
    bool isRecording = await AudioRecorder.isRecording;
    File file = widget.localFileSystem.file(recording.path);
    List<int> bytes=await file.readAsBytes();
    int len=await file.length();
    String base64str=base64.encode(bytes);
    print("  File length: $len");
    print("  File length: $bytes");
    print("  File base64: $base64str");
    setState(() {
      _recording = recording;
      _isRecording = isRecording;
    });
    _controller.text = recording.path;
    getAuth().then((token){
      getRadioInfo(token,base64str,len).then((resp){
        print(resp);
      });
    });
  }
  //获取access_token
  Future<String> getAuth() async{
    if(_authInfo!=null) return Future.value(_authInfo);
    String ak='ozt0wf9Un27lGz5XdSXzQpdk';
    String sk='oGMj53TgeI0t68hIAw5cOHq0CzgUPS1E';
    // 获取token地址
    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
    String getAccessTokenUrl = authHost
        // 1. grant_type为固定参数
        + "grant_type=client_credentials"
        // 2. 官网获取的 API Key
        + "&client_id=" + ak
        // 3. 官网获取的 Secret Key
        + "&client_secret=" + sk;

    BaseResp resp= await HttpUtils().post(getAccessTokenUrl);
    _authInfo=resp.data['access_token'];
    return resp.data['access_token'];

  }
  //语音信息
  Future<BaseResp> getRadioInfo(String accessToken,String base64Str,int len) async{
    String url='https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=$accessToken';
    Map data={"format":"wav","rate":16000,"dev_pid":80001,"channel":1,"token":accessToken,"cuid":"wondersgroup_zhrs","len":len,"speech":base64Str};
    Options options=Options();
    options.contentType=ContentType.json;
    return await HttpUtils().post(url,
        data: data,
        options: options
    );
  }

  Future requestPermission() async {
    // 申请权限
    Map<PermissionGroup, PermissionStatus> permissions =
    await PermissionHandler().requestPermissions([PermissionGroup.speech]);
    // 申请结果
    PermissionStatus permission =
    await PermissionHandler().checkPermissionStatus(PermissionGroup.speech);
    if (permission == PermissionStatus.granted) {
      print( "speech权限申请通过");
    } else {
      print( "speech权限申请被拒绝");
    }
  }
}